#include "control_of_elements.h"

control_of_elements::control_of_elements()
{
    this->setFlag(ItemIsMovable);


    is_1 = true;

    pix_1.load("1.png");
    pix_2.load("2.png");


    //开启定时器:
    startTimer(200);

}

QRectF control_of_elements::boundingRect() const
{
    return QRectF(-pix_1.width() / 2,-pix_1.height() / 2,pix_1.width(),pix_1.height());
}

void control_of_elements::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
{
    if(is_1)
    {
        painter->drawPixmap(boundingRect().topLeft(),pix_1);
        is_1 = !is_1;
    }
    else
    {
        painter->drawPixmap(boundingRect().topLeft(),pix_2);
        is_1 = !is_1;
    }


}

void control_of_elements::timerEvent(QTimerEvent *event)
{
    //定义随机数：
    qsrand((unsigned int)QTime::currentTime().msec());

    qreal boundary_right =  scene()->sceneRect().right() + boundingRect().width() / 2;                  //右边界
    qreal boundary_top =  scene()->sceneRect().top() + boundingRect().height() / 2;                      //上边界
    qreal boundary_bottom =  scene()->sceneRect().bottom() + boundingRect().height() / 2;        //下边界

    //超出右边界：
       if(pos().x() >= boundary_right)
       {
           setPos(scene()->sceneRect().left(),pos().y());
       }
       //超出上边界：
       if(pos().y() <= boundary_top)
       {
           setPos(pos().x(),scene()->sceneRect().bottom());
       }
       //超出下边界：
       if(pos().y() >= boundary_bottom)
       {
           setPos(pos().x(),scene()->sceneRect().top());
       }

       //按tm正玄波律动：
       qreal angle = (qrand() % 10) / 2;
       qreal dx = fabs(sin(angle * 3.14) * 100);
       qreal dy = (qrand() % 2 ) - 10;

       this->setPos(mapToParent(dx,dy));

    //更新，让图片跑起来：
       update(boundingRect());

}
